const initialState = {
  allChannelList: [] as channelListType[],
  // 声明状态,保存用户频道
  userChannelList: [] as channelListType[],

  // 声明一个切换tab栏的状态
  channel_id: 0,
};

export default function channelReducer(
  state = initialState,
  action: channelActionType
): typeof initialState {
  switch (action.type) {
    case 'channel/saveChannel':
      return {
        ...state,
        allChannelList: action.payload,
      };
    case 'channel/saveUserChannel':
      return {
        ...state,
        userChannelList: action.payload,
      };
    // 编写更新逻辑
    case 'channel/updateUserChannel':
      return {
        ...state,
        userChannelList: [...state.userChannelList, action.payload],
      };
    // 删除逻辑
    case 'channel/delUserChannel':
      return {
        ...state,
        userChannelList: state.userChannelList.filter(
          (item) => item.id !== action.payload
        ),
      };
    case 'channel/setChannel_Id':
      return {
        ...state,
        channel_id: action.payload,
      };
    default:
      return state;
  }
}

export type channelListType = {
  id: number;
  name: string;
};

// 定义action类型
export type channelActionType =
  | { type: 'channel/saveChannel'; payload: channelListType[] }
  | { type: 'channel/saveUserChannel'; payload: channelListType[] }
  //添加更新逻辑
  | { type: 'channel/updateUserChannel'; payload: channelListType }
  //
  | { type: 'channel/delUserChannel'; payload: number }
  // 设置channel_Id
  | { type: 'channel/setChannel_Id'; payload: number };
